package com.qili.controller.sys;


import cn.hutool.core.util.IdUtil;
import com.qili.core.utils.DictTypes;
import com.qili.entity.sys.*;
import com.qili.entity.base.BaseDict;
import com.qili.service.SysUserService;
import com.qili.service.base.BaseDictService;
import com.qili.service.sys.*;
import com.qili.service.sys.impl.EmailServiceImpl;
import com.qili.util.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * @author zhaoyongke
 * @date 2020/10/22
 * @description 用户注册
 */

@Controller
@Slf4j
@RequestMapping("/sys/register")
public class RegisterController {

    @Autowired
    SysUserService userService;
    @Autowired
    BaseDictService baseDictService;
    @Autowired
    SysRegionService sysRegionService;
    @Autowired
    private DataSourceTransactionManager manager;
    @Autowired
    EmailCodeService emailCodeService;
    @Autowired
    EmailServiceImpl emailService;
    @Autowired
    RoleService roleService;
    @Autowired
    RoleUserService roleUserService;
    @Autowired
    private MenuService menuService;


    private static final String CODE_ERROR = "code.error";

    /*
     *  跳转到注册页面
     * */
    @GetMapping(value = "goRegister")
    public String goRegister(Model model, HttpServletRequest request) {
        String gx_type = request.getParameter("_agx");// 供需类型  001  供方  002  需方
        String person_type = request.getParameter("_agz");// 个人或组织 001  个人  002  组织
        String ywType = request.getParameter("_alx");// 业务类型
        // （1）注册需方企业账号 registerXfcom
        // 获取单位性质
        List<BaseDict> dwlist = baseDictService.selectByTypeCode("DW001");
        // 学历类型
        List<BaseDict> edulist = baseDictService.selectByTypeCode("XL001");
        // 省
        List<SysRegion> provincelist = sysRegionService.selectListByLevelId("1");
        // 市
        List<SysRegion> citylist = sysRegionService.selectListByLevelId("2");
        model.addAttribute("gxType", gx_type);
        // 供需类型  001  供方  002  需方
        model.addAttribute("personType", person_type);
        // 个人或组织 001  个人  002  组织
        model.addAttribute("ywType", ywType);
        // 监理、咨询 、检测
        model.addAttribute("dwlist", dwlist);
        model.addAttribute("edulist", edulist);
        // 学历
        model.addAttribute("provincelist", provincelist);
        model.addAttribute("citylist", citylist);

        if ("002".equals(gx_type)) {
            //需方
            model.addAttribute("msg", "注册需方企业账号");
            return "/registerXfcom";
        } else if ("001".equals(gx_type)) {
            //供方
            if ("001".equals(person_type)) {
                //供方--个人
                model.addAttribute("msg", "注册供方个人账号");
                return "/registerGfPerson";
            } else if ("002".equals(person_type)) {
                //供方--组织
                model.addAttribute("msg", "注册供方企业账号");
                return "/registerXfcom";
            }
        }
        return "/registerXfcom";
    }

    /*
     *  注册协议
     * */

    @GetMapping(value = "regXy")
    public String regXy(Model model, HttpServletRequest request) {
        BaseDict dict = new BaseDict();
        dict.setBadtTypecode("ZCXY");
        dict.setBadtCode("001");
        BaseDict baseDict = baseDictService.select(dict).get(0);
        model.addAttribute("dict",baseDict.getBadtLevel9());
        return "/regXy";
    }


    /**
     * 邮件发送
     */
    @ResponseBody
    @RequestMapping(value = "sendEmail")
    public JsonUtil sendEmail(String email) {
        try {
            if(StringUtils.isBlank(email)){
                return JsonUtil.error("邮箱不能为空");
            }
            //校验改邮箱是否是已经注册的邮箱：
            SysUser sameEmailUser = new SysUser();
            sameEmailUser.setEmail(email);
            List<SysUser> select = userService.select(sameEmailUser);
            if(select.size() == 0){
                return JsonUtil.error("此邮箱未注册");
            }
            if(select.size()>1){
                return JsonUtil.error("此邮箱绑定了多个账号，请联系管理员处理");
            }
            emailService.sendEmailVerCode(email, VerifyCodeUtils.generateVerifyCode(6));
            return JsonUtil.sucess("邮件发送成功");
        } catch (Exception e) {
            e.printStackTrace();
            return JsonUtil.error("邮件发送失败" + e.getMessage());
        }
    }

    /**
     * 忘记密码
     *
     * @return
     */
    @GetMapping(value = "forgets")
    public String forget(String username,Model model) {
        if(StringUtils.isNotBlank(username)){
            SysUser sysUser = new SysUser();
            sysUser.setUsername(username);
            List<SysUser> select = userService.select(sysUser);
            if(select != null && select.size()>0){
                SysUser forgetUser = select.get(0);
                if(StringUtils.isNotBlank(forgetUser.getSource()) && !"003".equals(forgetUser.getSource())){
                    //非自行注册人员,跳转到forget2  找管理员重置密码
                    //从字典中获取平台管理员姓名以及联系电话
                    BaseDict baseDict = new BaseDict();
                    baseDict.setBadtTypecode(DictTypes.PLANTFORMADMIN.getType());
                    List<BaseDict> select1 = baseDictService.select(baseDict);
                    if(select1 != null && select1.size()>0){
                        BaseDict adminDict = select1.get(0);
                        model.addAttribute("adminName",StringUtils.isNotBlank(adminDict.getBadtLevel1())?adminDict.getBadtLevel1():"");
                        model.addAttribute("adminPhone",StringUtils.isNotBlank(adminDict.getBadtLevel2())?adminDict.getBadtLevel2():"");
                    }
                    return "/forget2";
                }
            }
        }
        return "/forget";
    }

    /**
     * 验证码时间验证
     *
     * @param list
     * @return
     */
    public Boolean ValCodeTime(List<EmailCode> list) {
        Date one = new Date();
        Date tow = DateUtil.parseDate(list.get(0).getCreateTime());
        long diff = one.getTime() - tow.getTime();
        long min = ((diff / (60 * 1000)));
        if (min > 1) {
            return false;
        }
        return true;
    }

    /**
     * 跳转修改密码
     *
     * @return
     */
    @GetMapping(value = "reset/{id}")
    public String reset(@PathVariable("id") String id, Model model) {
        model.addAttribute("id", id);
        return "/reset";
    }

    /**
     * 重置密码
     *
     * @param email
     * @param code
     * @return
     */
    @RequestMapping(value = "resetPassWord")
    public Object resetPassWord(String email, Model model, String code) {
        if (StringUtil.isNotBlank(email) && StringUtil.isNotBlank(code)) {
            SysUser sysUser = userService.selectByEmail(email);
            if (sysUser != null) {
                List<EmailCode> emailCodeList = emailCodeService.selectByEmail(email);
                if (emailCodeList.size() > 0) {
                    if (!(emailCodeList.get(0).getCode()).equalsIgnoreCase(code)) {
                        model.addAttribute("msg","验证码错误");
                        model.addAttribute("email",email);
                        return "/forget";
//                        return JsonUtil.error("验证码错误");
                    }
                   /* if (!ValCodeTime(emailCodeList)) {
                        return JsonUtil.error("验证码已过期");
                    }*/
                    model.addAttribute("id", sysUser.getId());
                    if (emailCodeList.get(0).getCode().equalsIgnoreCase(code)) {
                        return "/reset" /*+ sysUser.getId()*/;
                    }
                }
            }
            model.addAttribute("msg","此邮箱未注册");
            return "/forget";
        }
        model.addAttribute("msg","邮箱或者验证码不能为空");
        return "/forget";
    }

    /**
     * 修改密码
     *
     * @param id
     * @param passwordNew
     * @return
     */
    @RequestMapping("updatePassWord")
    public Object updatePassword(Model model,String id, String passwordNew, String passwordOld) {
        if(!passwordNew.equals(passwordOld)){
            model.addAttribute("msg","两次密码不一致");
            return "/reset";
        }else{
            boolean b = userService.checkUserPassword(passwordNew);
            if(!b){
                model.addAttribute("msg","密码格式不正确");
                return "/reset";
            }
        }
        if (StringUtil.isNotBlank(id) || StringUtil.isNotBlank(passwordNew)) {
            SysUser sysUser = userService.selectById(id);
            if (sysUser != null) {
                userService.updateById(id, passwordNew, sysUser.getUsername());
                model.addAttribute("message","密码重置成功");
                return "/reset";
            }
            return null;
        }
        return null;
    }

    /*
     *   隐私政策
     * */
    @GetMapping(value = "regYs")
    public String regYs(Model model, HttpServletRequest request) {
        BaseDict dict = new BaseDict();
        dict.setBadtTypecode("YSZC");
        dict.setBadtCode("001");
        BaseDict baseDict = baseDictService.select(dict).get(0);
        model.addAttribute("dict",baseDict.getBadtLevel9());
        return "/regYs";
    }

    /*
     * 获取城市(省市联动)
     */
    @ApiOperation(value = "/getCity", httpMethod = "GET", notes = "注册")
    @GetMapping(value = "getCity")
    @ResponseBody
    public JsonUtil getCity(String code) {
        JsonUtil reJs = new JsonUtil();
        try {
            SysRegion sys = new SysRegion();
            sys.setCode(code);
            List<SysRegion> list = sysRegionService.select(sys);
            SysRegion re = list.get(0);
            Long id = re.getId();
            List<SysRegion> ListRe = sysRegionService.selectListByParentId(id);

            reJs.setMsg("获取成功。");
            reJs.setFlag(true);
            reJs.setData(ListRe);
            return reJs;

        } catch (Exception e) {
            e.printStackTrace();
            reJs.setMsg("获取失败！！" + e.getMessage());
            reJs.setFlag(false);
            return reJs;
        }
    }

    /*
     * 获取业务类型
     */
    @ApiOperation(value = "/getYw", httpMethod = "GET", notes = "注册")
    @GetMapping(value = "getYw")
    @ResponseBody
    public JsonUtil getYw(String code) {
        JsonUtil reJs = new JsonUtil();
        try {
            List<BaseDict> list = baseDictService.selectYw(code);
            reJs.setMsg("获取成功。");
            reJs.setFlag(true);
            reJs.setData(list);
            return reJs;

        } catch (Exception e) {
            e.printStackTrace();
            reJs.setMsg("获取失败！！" + e.getMessage());
            reJs.setFlag(false);
            return reJs;
        }
    }

    /*
     * 获取咨询业务类型
     */
    @ApiOperation(value = "/getZxYw", httpMethod = "GET", notes = "注册")
    @GetMapping(value = "getZxYw")
    @ResponseBody
    public JsonUtil getZxYw(String typeCode, String code) {
        JsonUtil reJs = new JsonUtil();
        try {
            List<BaseDict> list = baseDictService.selectZxYw(typeCode);
            reJs.setMsg("获取成功。");
            reJs.setFlag(true);
            reJs.setData(list);
            return reJs;

        } catch (Exception e) {
            e.printStackTrace();
            reJs.setMsg("获取失败！！" + e.getMessage());
            reJs.setFlag(false);
            return reJs;
        }
    }

    /*
     *  注册方法
     * */
    @ApiOperation(value = "/register", httpMethod = "POST", notes = "注册")
    @PostMapping(value = "register")
    @ResponseBody
    public JsonUtil register(SysUser user, Model model, String rememberMe, HttpServletRequest request) {
        JsonUtil jsonUtil = new JsonUtil();
        try {
            String password = user.getPassword();
            jsonUtil.setFlag(false);
            user.setId(IdUtil.simpleUUID());
            user.setCreateDate(DateUtil.getCurrentDateTime());
            //设置用户来源为自行注册
            user.setSource("003");
            // 登录不能重复
            int count = userService.checkUser(user.getUsername());
            if (count != 0) {
                jsonUtil.setFlag(false);
                jsonUtil.setMsg("注册失败！" + "已经存在的用户名！");
                return jsonUtil;
            }
            if(StringUtils.isNotBlank(user.getEmail())){
                int i = userService.checkUserEmail(user.getEmail());
                if (i != 0) {
                    jsonUtil.setFlag(false);
                    jsonUtil.setMsg("注册失败！" + "已经存在的电子邮箱！");
                    return jsonUtil;
                }
            }
            //判断手机号码是否重复:
            JsonUtil checkPhoneResult = userService.checkSameTelephone(user);
            if(!checkPhoneResult.isFlag()){
                return checkPhoneResult;
            }
            // 添加用户
            userService.setUserFilePath(user);
            //密码加密
//            String pwd = Md5Util.getMD5(user.getPassword().trim(), user.getUsername().trim());
//            user.setPassword(pwd);
            user.setSource("003");
            userService.insertSelective(user);
            //添加默认角色
            List<String> initRoleList = new ArrayList<String>();
            initRoleList.add("register");
            //根据用户供需类型 赋予对应的角色
            String gxType = user.getGxType();
            if("001".equals(gxType)){
                // 供方
                initRoleList.add("gfperson");
            }else if("002".equals(gxType)){
                // 需方
                initRoleList.add("xfperson");
            }
            userService.setMenuAndRolesWhenRegist(user, initRoleList);
            jsonUtil.setFlag(true);
            jsonUtil.setMsg("注册成功");
        } catch (Exception e) {
            jsonUtil.setFlag(false);
            jsonUtil.setMsg("注册失败!" + e.getMessage());
        } finally {
            System.out.println("Finally");
        }
        return jsonUtil;
    }

    @GetMapping(value = "retosucess")
    public String retosucess(Model model, HttpServletRequest request) {
        return "/regSuccess";
    }


    /*
     * 获取城市(省市联动)
     * code 当前编码
     * levelId 要获取的级别
     */
    @ApiOperation(value = "/getOrganize", httpMethod = "GET", notes = "注册")
    @GetMapping(value = "getOrganize")
    @ResponseBody
    public JsonUtil getOrganize(SysRegion sys) {
        JsonUtil reJs = new JsonUtil();
        try {
            //SysRegion sys=new SysRegion();
            // sys.setCode(code);
            List<SysRegion> list = sysRegionService.select(sys);
            SysRegion re = list.get(0);
            Long id = re.getId();
            List<SysRegion> ListRe = sysRegionService.selectListByParentId(id);

            reJs.setMsg("获取成功。");
            reJs.setFlag(true);
            reJs.setData(ListRe);
            return reJs;

        } catch (Exception e) {
            log.error("获取城市信息失败！e:" + e);
            reJs.setMsg("获取失败！！" + e.getMessage());
            reJs.setFlag(false);
            return reJs;
        }
    }

    @ResponseBody
    @GetMapping(value = "/checkpwd")
    @ApiOperation(value = "/checkpwd", httpMethod = "GET", notes = "验证密码的有效性")
    public JsonUtil checkUserPwd(String pwd){
        JsonUtil jsonUtil = new JsonUtil();
        if(StringUtils.isNotBlank(pwd)){
            boolean b = userService.checkUserPassword(pwd);
            jsonUtil.setFlag(b);
        }
        return jsonUtil;
    }
}
